﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CNKI.TPI.Web.Base
{
    public class BaseController : Controller
    {
        protected ProxyGenerator generator;
        private Stopwatch sw;

        public BaseController()
        {
            generator = new ProxyGenerator();
            
        }
        //
        // 摘要:
        //     在调用操作方法前调用。
        //
        // 参数:
        //   filterContext:
        //     有关当前请求和操作的信息。
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        { 
            string controller = filterContext.RouteData.Values["controller"].ToString(); 
            string action = filterContext.RouteData.Values["action"].ToString();
            if (IsInfoLevelLog(controller, action))
            {
                LogOpr.Info(0, 0, controller + "Controller", action, "", "", "Recive request = " + Request.Url);
            }
            else
            {
                LogOpr.Debug(0, 0, controller + "Controller", action, "", "", "Recive request = " + Request.Url);
            }

            if (LogOpr.IsLogEnabled(CNKI.TPI.Web.Base.LogOpr.LogLevel.Debug))
            {
                sw = new Stopwatch();
                sw.Start();
            }
        }
        //
        // 摘要:
        //     在调用操作方法后调用。
        //
        // 参数:
        //   filterContext:
        //     有关当前请求和操作的信息。
        protected override void OnActionExecuted(ActionExecutedContext filterContext) 
        {
            if (LogOpr.IsLogEnabled(CNKI.TPI.Web.Base.LogOpr.LogLevel.Debug))
            {
                sw.Stop();
                string controller = filterContext.RouteData.Values["controller"].ToString();
                string action = filterContext.RouteData.Values["action"].ToString();
                LogOpr.Debug(1, sw.ElapsedMilliseconds, controller + "Controller", action, "", "", "End request");
            }
        }

        /// <summary>
        /// 是否输出为Info日志
        /// </summary>
        /// <param name="className"></param>
        /// <param name="funcName"></param>
        /// <returns></returns>
        private bool IsInfoLevelLog(string controller, string action)
        {
            bool result = true;
            if (("File".Equals(controller))
                && ("GetSmallPic".Equals(action) || "GetFirstSmallPic".Equals(action)))
            {
                result = false;
            }
            else if (("Home".Equals(controller))
                && ("GetMenuSession".Equals(action) || "SetMenuSession".Equals(action) || "HomeDataBase".Equals(action)))
            {
                result = false;
            }
            return result;
        }
    }
}
